
package metadatabrowser;

import at.fhj.itm.metadata.Column;
import at.fhj.itm.metadata.Constraint;
import at.fhj.itm.metadata.Table;
import at.fhj.itm.metadata.impl.postgres.PostgresTable;
import at.fhj.util.Pair;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.Viewer;

/**
 *
 * @author Seuchter
 */
public class TableContentProvider implements IStructuredContentProvider{



    public TableContentProvider()
    {
        
    }


    public String getPrimaryKeys(List<? extends Constraint> constraints)
    {
        StringBuilder sb = new StringBuilder();
        for(Constraint c : constraints)
        {
            if(c.getConstraintType().equals(Constraint.CONSTRAINT_TYPE_PRIMARY_KEY))
            {
                List<? extends Column> primaryColumns = c.getConstraintColumns();
                for(Column col : primaryColumns)
                {
                    sb.append(col.getName()).append(" ");
                }
            }
        }
        return sb.toString();
    }

    @Override
    public Object[] getElements(Object o)
    {
        if(! (o instanceof Table))
        {
            return null;
        }

        Table table = (Table) o;
        List<Pair<String,String>> properties = new ArrayList<Pair<String, String>>();
        properties.add(new Pair<String, String>("Name",table.getName()));
        
        if(table instanceof  PostgresTable)
        {
            PostgresTable t = (PostgresTable) table;
            properties.add(new Pair<String, String>("Oid",String.valueOf(t.getOid()) ));
            properties.add(new Pair<String, String>("Owner",  t.getOwner().getName().toString()));
        }
        String primaryKeys = getPrimaryKeys(table.getConstraints());
        if(primaryKeys.length() > 0)
        {
            properties.add(new Pair<String, String>("Primary Keys:",primaryKeys));
        }
        
        
        return properties.toArray();
    }

    @Override
    public void dispose()
    {
       
    }

    @Override
    public void inputChanged(Viewer viewer, Object o, Object o1)
    {

    }

}
